<html>
	<head>
		<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css">
		<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
		<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
		<script src="/jquery-tmpl-master/jquery.tmpl.min.js"></script>
		<script src="/image_to_photo.js"></script>
		<style type="text/css">
			.hidden{
				display: none;
			}
			
			#resultingImageHolder{
				background-color: green;
			}
			
			#workspace, #workspaceBackground, #resultingImageHolder{	
				width: 1000px;
				height: 800px;
			}
			
			#workspace, #workspaceBackground{	
				position : absolute;
				margin-top: 0px;
				margin-left: 0px;
			}
			
			#workspace img{
				z-index : 50;
			}
			
			#workspace div{
				z-index : 50;
			}
			
			#workspaceBackground{
				z-index : 0;
				background-color: white;//green;
			}
			
			#extendedCanvas, #extendedCanvasBorderOverlay{
				width: 800px;
				height: 600px;
				
				position : absolute;
				margin-top: 100px;
				margin-left: 100px;
				
				border: 1px solid red;
			}
			
			#extendedCanvas{
				z-index : 1;
				background-color: white;//yellow;
			}
			
			#extendedCanvasBorderOverlay{
				z-index: 200;
			}
			
			#canvas, #canvasBorderOverlay{
				width: 700px;
				height: 500px;
				
				position : absolute;
				margin-top: 150px;
				margin-left: 150px;
				
				border: 1px solid black;
			}
			
			#canvas{
				z-index : 2;
				background-color: white;//red;
			}
			
			#canvasBorderOverlay{
				z-index: 200;
			}
			
			#leftOverlay, #leftLeftOverlay, 
			#topOverlay, #topTopOverlay, 
			#rightOverlay, #rightRightOverlay, 
			#bottomOverlay, #bottomBottomOverlay{
				position : absolute;
				margin-top: 0px;
				margin-left: 0px;
			}
			
			#leftOverlay { /* Covers the left part of extended canvas */
				z-index : 100;
				
				width: 50px;
				margin-left: 100px;
				margin-top: 100px;
				height: 600px; /* Same as extended Canvas */
				background-color: rgba(248,248,255, 0.7);//rgba(230,26,26, 0.7);
			}
			
			#leftLeftOverlay { /* Covers the left part of the workspace */
				z-index : 101;
				
				width: 100px;
				height: 800px; /* Same as workspace */
				background-color: rgba(248,248,255, 0.9);//rgba(230,26,26, 0.9);
			}
			
			#topOverlay {
				z-index : 100;
				
				width: 700px; /* Same as canvas */ 
				margin-left: 150px;
				margin-top: 100px;
				height: 50px;
				background-color: rgba(248,248,255, 0.7);//rgba(230,26,26, 0.7);
			}
			
			#topTopOverlay {
				z-index : 101;
				
				width: 800px; /* Same as extended canvas */ 
				margin-left: 100px;
				height: 100px;
				background-color: rgba(248,248,255, 0.9);//rgba(230,26,26, 0.9);
			}
			
			#rightOverlay {
				z-index : 100;
				
				width: 50px;
				margin-left: 850px; /* 100 + 50 + 700 => workspace-left + extended canvas-left + width canvas  */
				margin-top: 100px;
				height: 600px; /* Same as extended Canvas */
				background-color: rgba(248,248,255, 0.7);//rgba(230,26,26, 0.7);
			}
			
			#rightRightOverlay {
				z-index : 101;
				
				width: 100px;
				margin-left: 900px;/* 100 + 800 => workspace-left + width extended canvas  */
				height: 800px; /* Same as workspace */
				background-color: rgba(248,248,255, 0.9);//rgba(230,26,26, 0.9);
			}
			
			#bottomOverlay {
				z-index : 100;
				
				width: 700px; /* Same as canvas */ 
				margin-left: 150px;
				margin-top: 650px; /* 100 + 50 + 500 => workspace-top + extended canvas-top + height canvas */
				height: 50px;
				background-color: rgba(248,248,255, 0.7);//rgba(230,26,26, 0.7);
			}
			
			#bottomBottomOverlay {
				z-index : 101;
				
				width: 800px; /* Same as extended canvas */ 
				margin-left: 100px;
				margin-top: 700px; /* 100 + 600 => workspace-top + height extended canvas */
				height: 100px;
				background-color: rgba(248,248,255, 0.9);//rgba(230,26,26, 0.9);
			}
			
			#workspace .ui-resizable-handle { 
				z-index: 1000 !important; 
			}
			
			.allowBorder .ui-resizable-handle { 
				background-color: black;
			}
		</style>
	</head>
	<body>
		<div id="test" >ok</div>
		<div id="imageUploadDialog">
			<input type='file' id="uploadImage1Input" />
			<input type='file' id="uploadImage2Input" />
			<input type='file' id="uploadImage3Input" />
			<input type='file' id="uploadImage4Input" />
			<input type='file' id="uploadImage5Input" />
		</div>
		<button id="openDialogBtn">edit</button>
		<div id="workspaceDialog">
			<button id="openToolboxBtn">toolbox</button>
			<button id="uploadImageBtn">uploadImage</button>
			<button id="mergeBtn">Merge</button>
			
			<div id="workspaceBackground"></div>
			<!-- Start overlays -->
			<div id="leftOverlay" class="overlayElement"></div>
			<div id="leftLeftOverlay" class="overlayElement"></div>
			<div id="topOverlay" class="overlayElement"></div>
			<div id="topTopOverlay" class="overlayElement"></div>
			<div id="rightOverlay" class="overlayElement"></div>
			<div id="rightRightOverlay" class="overlayElement"></div>
			<div id="bottomOverlay" class="overlayElement"></div>
			<div id="bottomBottomOverlay" class="overlayElement"></div>
			<div id="canvasBorderOverlay" class="overlayElement"></div>
			<div id="extendedCanvasBorderOverlay" class="overlayElement"></div>
			<!-- End overlays -->
			<div id="extendedCanvas"></div>
			<div id="canvas"></div>
			<div id="workspaceContainer">
				<div id="workspace">
					<img id="image1" src="/a.jpg" width="960" height="720" style="border: none;"/>
				</div>
			</div>
		</div>
		
		<div id="toolboxDialog">
			<input type="checkbox" name="allowBorder" id="allowBorder">Rand toestaan<br/>
			<input type="checkbox" name="keepProportions" id="keepProportions" checked="checked">Afmetingen behouden<br/>
		</div>
		
		<canvas id="resultingImageHolder" width="800" height="600"></canvas>
		
		<script id="workspace_image_template" type="text/x-jquery-tmpl">
				<img id="${image_id}" src="${image_url}" width="${image_width}" height="${image_height}" style="border: none;"/>
		</script>
				<!--img id="imageX" data-src="sourceUrl" width="200" height="200" style="border: none;"/-->
		
		<script type="text/javascript">
			//http://stackoverflow.com/questions/19262141/resize-image-with-javascript-canvas-smoothly
			//http://stackoverflow.com/questions/8093102/save-canvas-as-png-for-print !!!! super
			//http://stackoverflow.com/questions/12069852/html5-canvas-size-and-resolution
			$("#mergeBtn").click(function(e){
				var canvas = $("#resultingImageHolder")[0];
				var ctx = canvas.getContext("2d");
				ctx.clearRect(0,0,$(canvas).width(), $(canvas).height());
				//ctx.fillStyle = "red";
				//ctx.fillRect(0,0,50,50);
				drawImage(ctx, $("#workspace #image1"), $("#extendedCanvas"));
			});
			
			function drawImage(ctx, image, container){
				var img = new Image();
				img.src = $(image).attr('src');
				
				var args = [];
				args[0] = $(image).offset().left;
				args[1] = $(image).width();
				args[2] = $(image).offset().top;
				args[3] = $(image).height;
				
				args[4] = $(container).offset().left;
				args[5] = $(container).width();
				args[6] = $(container).offset().top;
				args[7] = $(container).height;
				
				args[8] = img.width;
				args[9] = img.height;
				
				var result = calculateDrawData(args);

				sourceX = result[0];
				sourceY = result[1];
				sourceWidth = result[2];
				sourceHeight = result[3];
				destX = result[4];
				destY = result[5];
				destWidth = result[6];
				destHeight = result[7];
				ctx.drawImage(img, sourceX, sourceY, sourceWidth, sourceHeight, destX, destY, destWidth, destHeight);
			}
		
			//imageUpload
			$("#imageUploadDialog").dialog({ autoOpen: false });
			$( "#uploadImageBtn" ).click(function() {
			  $( "#imageUploadDialog" ).dialog( "open" );
			});
			
			 function readURL(input, imageId) {
				if (input.files && input.files[0]) {
					var reader = new FileReader();
					
					reader.onload = function (e) {
						var image_template_data = [
							{
								image_id : imageId,
								image_url : e.target.result,
								image_width : e.width,
								image_height : e.height
							}
						];
						$.when(
							$( "#workspace_image_template" ).tmpl( image_template_data ).appendTo( "#workspace" )
						).then(
							init()
						);
					};
					
					reader.readAsDataURL(input.files[0]);
				}
			}
			
			$("#uploadImage1Input").change(function(){
				$('#workspace #image1').remove();
				readURL(this, 'image1');
			});
			$("#uploadImage2Input").change(function(){
				$('#workspace #image2').remove();
				readURL(this, 'image2');
			});
			$("#uploadImage3Input").change(function(){
				$('#workspace #image3').remove();
				readURL(this, 'image3');
			});
			$("#uploadImage4Input").change(function(){
				$('#workspace #image4').remove();
				readURL(this, 'image4');
			});
			$("#uploadImage5Input").change(function(){
				$('#workspace #image5').remove();
				readURL(this, 'image5');
			});
			
			$("#allowBorder").change(function(){
				if($(this).is(":checked")){
					$("#workspace").addClass("allowBorder");
				} else {
					$("#workspace").removeClass("allowBorder");
				}
			});
			$("#keepProportions").change(function(){
				$("#workspace img").each(function(){
					$(this).resizable( "destroy" );	
				});
				init();
			});
			
			//#####################################
			
			init();
			function init(){
			
				initOverlayElementEvent();
				initBodyMouseMoveEvent();
				//workspace
				$( "#workspaceDialog" ).dialog({ autoOpen: false });
				$( "#workspaceDialog" ).dialog( "option", "height", $("#workspace").height() + 75);
				$( "#workspaceDialog" ).dialog( "option", "modal", true);
				$( "#workspaceDialog" ).dialog( "option", "width", $("#workspace").width() + 50);
				$( "#workspaceDialog" ).on( "dialogclose", function(event, ui){
					$('#toolboxDialog').dialog('close');
				});
				$( "#openDialogBtn" ).click(function() {
				  $( "#workspaceDialog" ).dialog( "open" );
				});
				//toolbox
				$( "#toolboxDialog" ).dialog({ autoOpen: false });
				$( "#openToolboxBtn" ).click(function() {
				  $( "#toolboxDialog" ).dialog( "open" );
				});
				$("#workspace img").each(function(){
					$(this).resizable({
						handles: 'all',
						containment: $("#workspace"),
						aspectRatio: $("#keepProportions").is(':checked'),
						start: function(event, ui){
							startEditingImage();
						},
						stop: function(event, ui){
							stopEditingImage();
						}
					}).parent().draggable({
						containment: $("#workspace"),
						start: function(event, ui){
							startEditingImage();
						},
						stop: function(event, ui){
							stopEditingImage();
						}
					});
				});
				
				$('.overlayElement').on('mousedown', function(event){
					$('#workspace img').each(function(){
						if(isMouseIn($(this))){
							$(this).trigger(event);
						}
					});
				});
				
				function startEditingImage(){
					$('body').unbind('mousemove');
					$('.overlayElement').unbind('mousemove');
					$('.overlayElement').each(function(){
						$(this).removeClass('hidden');
					});
				}
				
				function stopEditingImage(){
					initOverlayElementEvent();
					initBodyMouseMoveEvent();
				}
				
				function initOverlayElementEvent(){
					$('.overlayElement').on('mousemove', function(event){
						var inImage = false;
						$('#workspace .ui-resizable-handle').each(function(){
							if(isMouseIn($(this))){
								inImage = true;
							}
						});
						if(inImage){
							$('.overlayElement:not(.hidden)').each(function(){
								$(this).addClass('hidden');
							});
						}
					});
				}
				
				function initBodyMouseMoveEvent(){
					//TODO make more performant
					$('body').on('mousemove', function(event){
						var inImage = false;
						$('#workspace .ui-resizable-handle').each(function(){
							if(isMouseIn($(this))){
								inImage = true;
							}
						});
						if(!inImage){
							$('.overlayElement.hidden').each(function(){
								$(this).removeClass('hidden');
							});
						}
					});
				}
				
				function isMouseIn(element){
					var gxstart = $(element).offset().left;
					var gxend = $(element).offset().left + $(element).width();
					var gystart = $(element).offset().top;
					var gyend = $(element).offset().top + $(element).height();  
					
					var mouseX = event.clientX;
					var mouseY = event.clientY;
					
					var mouseIsInElement = false;
					if( gxstart < mouseX ){
						if ( mouseX < gxend ){
							if(gystart < mouseY){
								if(mouseY < gyend){   
									mouseIsInElement = true;
								}
							}
						}
					}
					
					return mouseIsInElement;
				}
			}
			
			function resizeCanvasImage(img, canvas, maxWidth, maxHeight) {
				var imgWidth = img.width, 
					imgHeight = img.height;

				var ratio = 1, ratio1 = 1, ratio2 = 1;
				ratio1 = maxWidth / imgWidth;
				ratio2 = maxHeight / imgHeight;

				// Use the smallest ratio that the image best fit into the maxWidth x maxHeight box.
				if (ratio1 < ratio2) {
					ratio = ratio1;
				}
				else {
					ratio = ratio2;
				}

				var canvasContext = canvas.getContext("2d");
				var canvasCopy = document.createElement("canvas");
				var copyContext = canvasCopy.getContext("2d");
				var canvasCopy2 = document.createElement("canvas");
				var copyContext2 = canvasCopy2.getContext("2d");
				canvasCopy.width = imgWidth;
				canvasCopy.height = imgHeight;  
				copyContext.drawImage(img, 0, 0);

				// init
				canvasCopy2.width = imgWidth;
				canvasCopy2.height = imgHeight;        
				copyContext2.drawImage(canvasCopy, 0, 0, canvasCopy.width, canvasCopy.height, 0, 0, canvasCopy2.width, canvasCopy2.height);


				var rounds = 2;
				var roundRatio = ratio * rounds;
				for (var i = 1; i <= rounds; i++) {
					console.log("Step: "+i);

					// tmp
					canvasCopy.width = imgWidth * roundRatio / i;
					canvasCopy.height = imgHeight * roundRatio / i;

					copyContext.drawImage(canvasCopy2, 0, 0, canvasCopy2.width, canvasCopy2.height, 0, 0, canvasCopy.width, canvasCopy.height);

					// copy back
					canvasCopy2.width = imgWidth * roundRatio / i;
					canvasCopy2.height = imgHeight * roundRatio / i;
					copyContext2.drawImage(canvasCopy, 0, 0, canvasCopy.width, canvasCopy.height, 0, 0, canvasCopy2.width, canvasCopy2.height);

				} // end for


				// copy back to canvas
				canvas.width = imgWidth * roundRatio / rounds;
				canvas.height = imgHeight * roundRatio / rounds;
				canvasContext.drawImage(canvasCopy2, 0, 0, canvasCopy2.width, canvasCopy2.height, 0, 0, canvas.width, canvas.height);
			}
		</script>
	</body>
</html>